using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WaveSurface : MonoBehaviour
{
    public float waterPos;
    public float buoyancyFactor;
    public float waveHeightFactor;
    public float waveSpeedFactor;
    private void OnTriggerStay2D(Collider2D collision)
    {
        var wave = Mathf.Sin(collision.transform.position.x + Time.time * waveSpeedFactor) * waveHeightFactor;
        float realWaterPos = waterPos + wave;

        var curCtrller = collision.GetComponent<PlayerController>();
        if (curCtrller)
        {
            var curTorso = collision.GetComponent<Rigidbody2D>();
            var newWaterState = realWaterPos + 0.3f >= curTorso.position.y;
            if (newWaterState != curCtrller.InWater)
            {
                curCtrller.SetWaterState(newWaterState);
                FXManager.Instance.ShowFX(2, curTorso.position, Quaternion.identity);
            }
            if (curTorso.position.y > realWaterPos)
                return;

            curTorso.AddForce(Vector2.up * (curTorso.gravityScale * curTorso.mass * 9.8f + buoyancyFactor * (realWaterPos - curTorso.position.y)));
        }

        var curItem = collision.GetComponent<Item>();
        if (curItem)
        {
            var curRigid = collision.GetComponent<Rigidbody2D>();
            var newWaterState = curRigid.position.y < realWaterPos;
            if (newWaterState != curItem.inWater)
            {
                curItem.inWater = newWaterState;
                FXManager.Instance.ShowFX(2, curRigid.position, Quaternion.identity);
            }
            if (curRigid.position.y > realWaterPos)
                return;

            curRigid.AddForce(Vector2.up * (curRigid.gravityScale * curRigid.mass * 6.6f + buoyancyFactor * (realWaterPos - curRigid.position.y)));
        }

        var curGlove = collision.GetComponent<Glove>();
        if (curGlove)
        {
            var curRigid = collision.GetComponent<Rigidbody2D>();
            var newWaterState = curRigid.position.y < realWaterPos;
            if (newWaterState != curGlove.InWater)
            {
                curGlove.InWater = newWaterState;
                FXManager.Instance.ShowFX(2, curRigid.position, Quaternion.identity);
            }
        }
    }
}
